﻿using Swift.Lib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CB.Logic
{
    /// <summary>
    /// 事件监听管理    
    /// </summary>
    public class EventManager
    {
        public static EventManager Instance = new EventManager();

        public delegate void EventListener(Dbase db);
        private Dictionary<string, List<EventListener>> EventContainer = new Dictionary<string, List<EventListener>>();

        /// <summary>
        /// 触发事件
        /// </summary>
        public void TriggerEvent(string name, Dbase db = null)
        {
            if (EventContainer.TryGetValue(name, out List<EventListener> list))
            {
                foreach (var action in list)
                {
                    action?.Invoke(db);
                }
            }
        }

        /// <summary>
        /// 添加事件监听
        /// </summary>
        public void AddListener(string name, EventListener action)
        {
            if (!EventContainer.ContainsKey(name))
            {
                EventContainer[name] = new List<EventListener>();
            }

            EventContainer[name].Add(action);
        }

        /// <summary>
        /// 移除事件监听
        /// </summary>
        public void RemoveListenet(string name, EventListener action)
        {
            if (EventContainer.TryGetValue(name, out List<EventListener> list))
            {
                list.Remove(action);

                if(list.Count == 0)
                {
                    EventContainer.Remove(name);
                }
            }
        }
    }
}
